// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package exploitdb

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	exploitmodels "github.com/vulsio/go-exploitdb/models"

	"github.com/openclarity/openclarity/scanner/common"
	"github.com/openclarity/openclarity/scanner/families"
	"github.com/openclarity/openclarity/scanner/families/exploits/exploitdb/config"
	"github.com/openclarity/openclarity/scanner/families/exploits/types"
)

const ScannerName = "exploitdb"

type Scanner struct {
	config config.Config
}

func New(_ context.Context, _ string, config types.ScannersConfig) (families.Scanner[[]types.Exploit], error) {
	return &Scanner{
		config: config.ExploitDB,
	}, nil
}

func (s *Scanner) Scan(ctx context.Context, inputType common.InputType, userInput string) ([]types.Exploit, error) {
	if !inputType.IsOneOf(common.CSV) {
		return nil, fmt.Errorf("unsupported input type=%s", inputType)
	}

	cveIDs := stringToArray(userInput)
	if cveIDs == nil {
		return nil, nil
	}

	// get exploits from exploit db
	exploits, err := s.getExploitsFromCVEIDs(ctx, cveIDs)
	if err != nil {
		return nil, fmt.Errorf("failed to get exploits from cve ids: %w", err)
	}

	return exploits, nil
}

func (s *Scanner) getExploitsFromCVEIDs(ctx context.Context, cveIDs []string) ([]types.Exploit, error) {
	var ret []types.Exploit

	prefix, err := url.JoinPath(s.config.BaseURL, "cves")
	if err != nil {
		return nil, fmt.Errorf("failed to join URLPath: %w", err)
	}

	responses, err := getExploitsViaHTTP(ctx, cveIDs, prefix)
	if err != nil {
		return nil, fmt.Errorf("failed to get exploits via HTTP: %w", err)
	}

	for _, res := range responses {
		var exps []exploitmodels.Exploit
		if err := json.Unmarshal([]byte(res.json), &exps); err != nil {
			return nil, fmt.Errorf("failed to unmarshal json: %w", err)
		}

		exploits := convertToCommonExploits(exps, res.request.cveID)
		ret = append(ret, exploits...)
	}

	return ret, nil
}
